<template>
  <div ref="editor"></div>
</template>

<script>
import E from 'wangeditor'
import { updtaCourseImage } from '@/services/course'
export default {
  props: {
    value: {
      type: String,
      default: '课程详情'
    }
  },
  name: 'TextEditor',
  // 元素加载完成后的钩子函数
  mounted () {
    // 富文本编辑器初始化
    this.initEditor()
  },
  data () {
    return {
      editor: null,
      isLoaded: false
    }
  },
  methods: {
    initEditor () {
      const editor = new E(this.$refs.editor)
      // 需要在创建之前进行时间设置
      editor.config.onchange = value => {
        this.$emit('input', value)
      }
      // 配置自定义的图片上传功能
      editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
        const fd = new FormData()
        fd.append('file', resultFiles[0])
        const { data } = await updtaCourseImage(fd)
        if (data.code === '000000') {
          insertImgFn(data.data.name)
        }
      }
      editor.create()
      editor.txt.html(this.value)
      this.editor = editor
    }
  },
  watch: {
    value () {
      if (this.isLoaded === false) {
        this.editor.txt.html(this.value)
        this.isLoaded = true
      }
    }
  }
}
</script>

<style lang="scss" scoped ></style>
